<script setup lang="ts">
  import CustomSingleSelect from '@/views/order/custom/form/component-list/CustomSingleSelect.vue'
  import {
    ChildFormConfig,
    ComponentListItem,
    DataConnectConfig,
    DataConnectFieldFillMode,
    DataConnectTableFieldType,
  } from '@/views/order/custom/hooks/types'
  import { computed, PropType, ref, watch } from 'vue'
  import _ from 'lodash'

  defineOptions({
    name: 'OrderCustomDataConnectFieldFillSetModal',
  })

  const props = defineProps({
    sourceFieldList: {
      type: Array as PropType<Array<{ label: string; value: DataConnectTableFieldType }>>,
      required: true,
    },
    defaultRules: {
      type: Array as PropType<DataConnectConfig['fillRules']>,
      default: () => [],
    },
    inputComponentList: {
      type: Array as PropType<Array<ComponentListItem | ChildFormConfig>>,
      default: () => [],
    },
  })

  const emits = defineEmits<{
    (e: 'update', value: DataConnectConfig['fillRules']): void
  }>()

  // 选择的列表
  const selectionList = ref<DataConnectConfig['fillRules']>([])

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 目标字段下拉选项
  const targetFieldOptions = computed(() => {
    return props.inputComponentList.map((item) => {
      return {
        label: item.label,
        value: item.id,
      }
    })
  })

  /**
   * 字段添加下拉选项
   */
  const fieldAddOptions = computed(() => {
    const formFieldList = form.value.map((item) => item.fromField)
    return props.sourceFieldList.filter((field) => !formFieldList.includes(field.value))
  })

  // 填充方式下拉选项
  const fillModeOptions: Array<{ label: string; value: DataConnectFieldFillMode }> = [
    { label: '不填充', value: 0 },
    { label: '填充到新字段', value: 1 },
    { label: '填充到已有的字段', value: 2 },
  ]

  // 表单对象
  const form = ref<DataConnectConfig['fillRules']>([])

  /**
   * 添加字段事件
   * @param field - 字段
   */
  const handleFieldAdd = (field: (typeof props.sourceFieldList)[0]) => {
    form.value.push({
      fillMode: 0,
      fromFieldName: field.label,
      fromField: field.value,
      toFieldName: '',
      toFieldId: '',
    })
  }

  /**
   * 删除事件
   * @param {number} index - 字段索引
   */
  const handleDel = (index: number) => {
    form.value.splice(index, 1)
  }

  /**
   * 隐藏弹窗
   */
  const hideDialog = () => {
    form.value.length = 0
    visible.value = false
  }

  /**
   * 确定事件
   */
  const onConfirm = () => {
    emits('update', _.cloneDeep(form.value))
    hideDialog()
    form.value = form.value.map((item) => {
      if (item.fillMode !== 2) {
        item.toFieldId = ''
        item.toFieldName = ''
      }
      return item
    })
  }

  /**
   * 批量填充方式弹出框显示状态
   * @param {0|1|2} mode - 填充方式
   */
  const handleMultipleFillMode = (mode: 0 | 1 | 2) => {
    form.value = form.value.map((item) => {
      item.fillMode = mode
      return item
    })
  }

  /**
   * 表格选择事件
   * @param {DataConnectConfig['fillRules']} list - 选择的列表
   */
  const handleSelectionChange = (list: DataConnectConfig['fillRules']) => {
    selectionList.value = _.cloneDeep(list)
  }

  watch(visible, (value) => {
    if (value && props.defaultRules.length > 0) {
      form.value = _.cloneDeep(props.defaultRules)
    }
  })
</script>

<template>
  <h-dialog v-model="visible" title="字段填充设置" :width="800" @close="hideDialog">
    <div class="container">
      <div class="btn-group">
        <h-plain-button :disabled="selectionList.length === 0" @click="handleMultipleFillMode(0)"
          >不填充</h-plain-button
        >
        <h-plain-button :disabled="selectionList.length === 0" @click="handleMultipleFillMode(1)"
          >填充到新字段</h-plain-button
        >
        <h-plain-button :disabled="selectionList.length === 0" @click="handleMultipleFillMode(2)"
          >填充到已有的字段</h-plain-button
        >
        <el-dropdown trigger="click" :hide-on-click="false">
          <h-button>
            添加字段

            <el-icon>
              <arrow-down></arrow-down>
            </el-icon>
          </h-button>

          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                v-for="(field, fieldIndex) in fieldAddOptions"
                :key="fieldIndex"
                @click="handleFieldAdd(field)"
                >{{ field.label }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <el-table
        :data="form"
        :border="true"
        :max-height="450"
        width="100%"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择 -->
        <el-table-column type="selection" width="50" :align="'center'" />

        <!-- 序号 -->
        <el-table-column type="index" label="序号" width="50" :align="'center'" />

        <!-- 源字段 -->
        <el-table-column type="index" label="源字段" min-width="100">
          <template #default="{ row }">
            <custom-single-select
              v-model="row.fromField"
              disabled
              :options="props.sourceFieldList"
              placeholder="请选择源字段"
            />
          </template>
        </el-table-column>

        <!-- 填充方式 -->
        <el-table-column label="填充方式" width="170">
          <template #default="{ row }">
            <custom-single-select
              v-model="row.fillMode"
              :options="fillModeOptions"
              placeholder="请选择填充方式"
              :clear="false"
            />
          </template>
        </el-table-column>

        <!-- 目标字段 -->
        <el-table-column type="index" label="目标字段" width="280">
          <template #default="{ row }">
            <custom-single-select
              v-model="row.toFieldNo"
              :disabled="[0, 1].includes(row.fillMode)"
              :options="targetFieldOptions"
              placeholder="请选择目标字段"
              :clear="false"
            />
          </template>
        </el-table-column>

        <el-table-column label="操作" width="50">
          <template #default="{ $index }">
            <h-link type="error" @click="handleDel($index)">删除</h-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <h-button type="primary" is-modal @click="onConfirm">确定</h-button>
      <h-button is-modal @click="hideDialog">取消</h-button>
    </template>
  </h-dialog>
</template>

<style scoped lang="scss">
  .fill-mode-multiple-container {
    display: flex;
    column-gap: 4px;
  }

  .fill-mode-header {
    display: flex;
    column-gap: 8px;

    .operate {
      color: #007cff;
      cursor: pointer;
      user-select: none;
    }
  }

  .container {
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    row-gap: 8px;

    .btn-group {
      display: flex;
      column-gap: 4px;
    }
  }
</style>
